﻿namespace MiniX.Manage.Extensions
{
    using FluentScheduler;
    using MiniX.Manage.Data;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Serilog;
    using Serilog.Core;
    using System;
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;
    using MiniX.Utility.Config;
    using MiniX.Manage.Filters;
    using Microsoft.Extensions.DependencyInjection;

    /// <summary>
    /// TaskHelper
    /// </summary>
    public class TaskHelper: Registry
    {
        /// <summary>
        /// Log变量
        /// </summary>
        public Logger log;

        public TaskHelper()
        {
            // 初始化日志
            log = new LoggerConfiguration()
             .ReadFrom.Configuration(new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
             .Build())
             .CreateLogger();

            DoTask();
        }

        /// <summary>
        /// 执行任务
        /// </summary>
        private void DoTask()
        {
            NonReentrantAsDefault();
            Schedule(() =>
            {
                var task = Task.Run(async () =>
                {
                    await ClearLogs();
                });

            }).WithName("ClearLogs").ToRunEvery(1).Days().At(2, 1); // 每天凌晨2点1分执行
        }

        /// <summary>
        /// 清除日志
        /// </summary>
        /// <returns></returns>
        private async Task ClearLogs()
        {
            try
            {
                // 连接数据库
                var connection = AppSettingsFilter.GetSetting("ConnectionStrings:PRO_LOCAL");
                var server_version = ServerVersion.AutoDetect(connection);
                var dbContextOption = new DbContextOptions<MiniXManageContext>();
                var optBuilder = new DbContextOptionsBuilder<MiniXManageContext>(dbContextOption);
                optBuilder.UseMySql(connection, server_version);

                using (var context = new MiniXManageContext(optBuilder.Options))
                {
                    // 读取数据库配置删除多少天之前的数据
                    var days = 0;
                    var item = context.mini_setting_info.FirstOrDefault(t => t.setting_info_id == 1406);
                    if (item != null)
                    {
                        days = Convert.ToInt32(item.info_value);
                    }
                    // 清除日志
                    var logs = await context.mini_logs.Where(t => DateTime.Now.Date >= t.created_at.AddDays(days).Date).ToListAsync();
                    logs.ForEach(c =>
                    {
                        var log_id = c.log_id;
                    });

                    context.mini_logs.RemoveRange(logs);
                    context.SaveChanges();
                };

            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> 清除日志");
            }
        }
    }
}
